package com.bjpowernode.web;

import com.bjpowernode.entity.TCustomer;
import com.bjpowernode.query.TCustomerQuery;
import com.bjpowernode.result.R;
import com.bjpowernode.service.TCustomerService;
import com.github.pagehelper.PageInfo;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;
import java.net.URLEncoder;

/**
 *
 */
@RestController
@Slf4j
@RequestMapping("/api/customer")
public class TCustomerController {

    @Resource
    private TCustomerService tCustomerService;

    @PostMapping("")
    public R convertCustomerSave(@Validated TCustomerQuery tCustomerQuery,
                                 @RequestHeader(value = "Authorization")String jwt) {
        log.info("要转换的客户信息 : {}" , tCustomerQuery);
        tCustomerQuery.setJwt(jwt);
        boolean save = tCustomerService.saveCustomer(tCustomerQuery);
        return save ? R.OK() : R.FAIL();
    }

    @GetMapping("page")
    public R customerByPage(@RequestParam(value = "current", defaultValue = "1") Integer current) {
        log.info("分页查询第 {} 页" , current);
        PageInfo<TCustomer> tCustomerPageInfo = tCustomerService.getCustomerByPage(current);
        log.info("值 : " + tCustomerPageInfo.getPageSize());
        return R.OK(tCustomerPageInfo);
    }

    @GetMapping("exportExcel")
    public void batchExportExcel(HttpServletResponse response,
                                 @RequestParam(value = "ids" , required = false)String ids) throws IOException {
        // 设置响应的内容类型 : excel的 application/vnd.openxmlformats-officedocument.spreadsheetml.sheet -> xlsx
        // application/vnd.ms-excel  -> 对于.xls文件
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setCharacterEncoding("utf-8");
        // 设置响应头
        String fileName = URLEncoder.encode("客户数据", "UTF-8");
        String headerValue = "attachment; filename*=UTF-8''" + fileName + ".xlsx";
        response.setHeader("Content-Disposition", headerValue);

        tCustomerService.batchExportExcel(response.getOutputStream() , ids);
    }

    @GetMapping("{id}")
    public R loadCustomerDetail(@PathVariable(value = "id")Integer id) {
        log.info("要加载的客户详情id");
        TCustomer tCustomerList = tCustomerService.loadCustomerDetail(id);
        return R.OK(tCustomerList);
    }
}
